package com.fuyun.rpc.common.serializer;

import java.io.*;

/**
 * @author: zrq1351
 * @date: 2025/2/14
 */
public class JdkSerializer implements Serializer {
	@Override
	public <T> byte[] serialize(T obj) {
		try (ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
			ObjectOutputStream outputStream = new ObjectOutputStream(arrayOutputStream)) {
			outputStream.writeObject(obj);
			return arrayOutputStream.toByteArray();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> T deserialize(byte[] bytes, Class<T> clazz) {
		try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
			ObjectInputStream inputStream = new ObjectInputStream(byteArrayInputStream)) {
			return (T)inputStream.readObject();
		} catch (IOException | ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
}